﻿using BattleFury.Lib.Maps;
using BattleFury.Lib.Tiles;
using Cartographer.Adapters;
using Cartographer.Tiled;
using Microsoft.Xna.Framework;
using System.Xml.Linq;

namespace BattleFury.Cartographer
{
	public class TiledAdapter
		: Adapter<TiledMap, TileMap>
	{
		public TiledAdapter(string filename)
			: base(filename)
		{
			
		}

		public override void Initialize()
		{
			CartographerObject = new TiledMap(XDocument.Load(Filename));
		}

		public override TileMap Adapt()
		{
			var mapSize = new Vector2(CartographerObject.Width, CartographerObject.Height);
			var tileSize = new Vector2(CartographerObject.TileWidth, CartographerObject.TileHeight);
			var ret = new TileMap(mapSize)
			{
					
			};

			foreach (var data in CartographerObject.Layers)
			{
				if (data.Name == "Collisions")
				{
					var layer = new CollisionLayer(mapSize, tileSize)
					{
						Name = data.Name,
						IsVisible = false,
					};
					var tx = 0;
					var ty = 0;
					foreach (var tileData in data.Tiles)
					{
						if (tileData.Gid - 1 < 0)
						{
							tx++;
							if (!(tx >= mapSize.X)) continue;
							tx = 0;
							ty++;
							continue;
						}
						var tile = new CollisionTile();
						layer.SetTile(tx, ty, tile);
						tx++;
						if (!(tx >= mapSize.X)) continue;
						tx = 0;
						ty++;
					}
					ret.AddLayer(layer);
				}
				else
				{
					var layer = new TileLayer(mapSize, tileSize)
					{
						Name = data.Name,
						IsVisible = data.Visible,
					};
					var tx = 0;
					var ty = 0;
					foreach (var tileData in data.Tiles)
					{
						var tile = new Tile
						{
							Index = tileData.Gid - 1,
							Size = tileSize,
							Position = new Vector2(tx*tileSize.X, ty*tileSize.Y),
							TilesetAssetName = CartographerObject.Tilesets[0].Source
						};
						if (tile.Index >= 0) layer.SetTile(tx, ty, tile);
						if (tile.Index < 0) layer.SetTile(tx, ty, null);
						tx++;
						if (!(tx >= mapSize.X)) continue;
						tx = 0;
						ty++;
					}
					ret.AddLayer(layer);
				}
			}

			return ret;
		}
	}
}